package myspringmvc;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/youhua_actor5.do")
public class DispatcherServlet3 extends ViewBaseServlet {

    private Map<String,Object> beanMap = new HashMap<>();

    @Override
    public void init() throws ServletException {
        super.init();
        try {
            InputStream applicationContext = getClass().getClassLoader().getResourceAsStream("applicationContext.xml");
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(applicationContext);
            NodeList beanNodeList = document.getElementsByTagName("bean");
            for (int i = 0; i < beanNodeList.getLength(); i++) {
                Node beanNode = beanNodeList.item(i);
                if (beanNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element beanElement = (Element) beanNode;
                    String id = beanElement.getAttribute("id");
                    String aClass = beanElement.getAttribute("class");
                    Class<?> controllerObj = Class.forName(aClass);
                    Object o = controllerObj.newInstance();
                    beanMap.put(id,o);
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String servletPath = req.getServletPath();
        servletPath = servletPath.substring(1);
        int lastIndexOf = servletPath.lastIndexOf(".do");
        servletPath = servletPath.substring(0, lastIndexOf);
        Object obj = beanMap.get(servletPath);

        req.setCharacterEncoding("utf-8");
        String operate = req.getParameter("operate");
        if (operate == null || "".equals(operate)) {
            operate = "index";
        }
        try {
            Method[] methods = obj.getClass().getDeclaredMethods();
            for (Method method: methods) {
                //获取参数
                if (operate.equals(method.getName())) {
                    Parameter[] parameters = method.getParameters();
                    Object[] parameterValues = new Object[parameters.length];
                    for (int i = 0; i < parameters.length; i++) {
                        Parameter parameter = parameters[i];
                        String name = parameter.getName();
                        if ("request".equals(name)) {
                            parameterValues[i] = req;
                        } else if ("response".equals(name)) {
                            parameterValues[i] = resp;
                        } else if ("session".equals(name)) {
                            parameterValues[i] = req.getSession();
                        } else {
                            String reqParameter = req.getParameter(name);
                            Class<?> parameterType = parameter.getType();
                            Object parameterObj = reqParameter;
                            if (parameterObj != null) {
                                if (parameterType.equals("java.lang.Integer")) {
                                    parameterObj = Integer.parseInt(reqParameter);
                                }
                            }

                            parameterValues[i] = parameterObj;
                        }
                    }
                    //方法调用
                    method.setAccessible(true);
                    Object invoke = method.invoke(obj, parameterValues);
                    /**
                     * 统一处理返回操作
                     */
                    if (invoke != null) {
                        String invoke1 = (String) invoke;
                        boolean b = invoke1.startsWith("redirect:");
                        if (b) {
                            String uri = invoke1.substring("redirect:".length());
                            resp.sendRedirect(uri);
                        } else {
                            if (invoke1.equals("error")) {
                                System.out.println("error!!!");
                            } else {
                                super.processTemplate(invoke1,req,resp);
                            }
                        }
                    }
                }
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
